/**
 * 
 */
package com.etlmaster.executor.steps.load;

import java.util.HashMap;
import java.util.Map;

import com.etlmaster.core.DataSourceDefine;
import com.etlmaster.core.DataSourceHolder;
import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.DpExecutorUtils;
import com.etlmaster.executor.utils.Shell;
import com.etlmaster.executor.utils.StepState;

/**
 * @author FengL
 * 
 */

@StepInstruction("impFileToDB2")
public class ImpFileToDB2Step extends Step {

	private ImpFileToDB2StepMeta meta;

	/**
	 * @param meta
	 */
	public ImpFileToDB2Step(StepMeta meta) {
		super(meta);
		this.meta = (ImpFileToDB2StepMeta) meta;
		// TODO Auto-generated constructor stub
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.asiainfo.dacp.dp.executor.Step#handle()
	 */
	@Override
	protected int handle() {
		String dsType = DataCollectionUtils.getDsType(meta.getDsName());
		if (!dsType.equalsIgnoreCase("db2")) {
			meta.log("WARN", "选择非db2数据库({})", meta.getDsName());
			return StepState.RUNNING_FAILED;
		}

		DataSourceDefine def = DataSourceHolder.getInstance()
				.getDataSourceDefine(meta.getDsName());
		if (def != null) {
			meta.setUserName(def.getUsername());
			meta.setPassword(def.getPassword());
			meta.setLocalAlias(def.getAlias()[0]);
		} else {
			meta.log("WARN", "严重告警：未获取到 数据源{} (用户名{} 密码{} 本地别名{})未取到",
					meta.getDsName(), meta.getUserName(), meta.getPassword(),
					meta.getLocalAlias());
			return StepState.RUNNING_FAILED;
		}
		int flag = StepState.RUNNING_SUCCESSED;
		Map<String, Object> tmpMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			if (meta.getFiledSpit().equals("^A")) {
				meta.setFiledSpit("0x01");
			} else if (meta.getFiledSpit().equals("TAB")) {
				meta.setFiledSpit("\t");
			} else if (meta.getFiledSpit().equals("comma")) {
				meta.setFiledSpit(",");
			}
			Shell.ShellCommandExecutor executor = new Shell.ShellCommandExecutor(
					new String[] {});
			String command = createLoadShellParams();
			meta.log("INFO", "执行import命令:{}" + command);
			executor.runCmd(command);
			int rtnFlag = executor.getExitCode();
			String logfileString = executor.getOutput();
			meta.log("INFO", "执行输出结果：{}", logfileString);
			int pos = logfileString.indexOf("SQLCODE:[");
			String line2 = logfileString.substring(pos, logfileString.length());
			meta.log("INFO", ">>>>>>>>>>>>>>>>>" + line2);
			String[] results = line2.split("@");
			for (String output : results) {
				String[] kv = output.split(":");
				tmpMap.put(kv[0], kv[1].subSequence(1, kv[1].length() - 1));
			}
			if ("0".equals(tmpMap.get("SQLCODE"))) {
				meta.log("INFO", "加载执行成功！");
				tmpMap.put("success", true);
			} else {
				meta.log("INFO", "加载执行失败！");
				tmpMap.put("success", false);
				flag = StepState.RUNNING_FAILED;
			}
			if ((Boolean) tmpMap.get("success")) {
				resultMap.put("status", 0);
				resultMap.put("succ_num", tmpMap.get("V_LOADED"));
				resultMap.put("ref_num", tmpMap.get("V_ROWS_REJECTED"));
				resultMap.put("load_num", tmpMap.get("V_ROWS_READ"));
				resultMap.put("error_msg", tmpMap.get("SQLERR"));
			} else {
				resultMap.put("status", -1);
				resultMap.put("succ_num", tmpMap.get("V_LOADED"));
				resultMap.put("ref_num", tmpMap.get("V_ROWS_REJECTED"));
				resultMap.put("load_num", tmpMap.get("V_ROWS_READ"));
				resultMap.put("error_msg", tmpMap.get("SQLERR"));
			}
		} catch (Exception e) {
			meta.log("ERROR", "装载过程失败!{}", e.getMessage());
			return StepState.RUNNING_FAILED;
		}
		meta.getStepState().getReturnValue().put("loadInfo", resultMap);
		return flag;
	}

	private String createLoadShellParams() {
		String loadCmd = DataCollectionUtils.getProperties("db2.loadCmd");
		Map<String, String> data = new HashMap<String, String>();
		StringBuilder params = new StringBuilder();
		data.put("filesPath", (String) meta.getFileName());
		data.put("targetTable", meta.getTableName());
		data.put("loadDelimiter", meta.getFiledSpit());
		String cmd = DpExecutorUtils.variableSubstitution(loadCmd, data);
		params.append(meta.getTableName() + " ").append("0" + " ")
				.append(meta.getLocalAlias() + " ")
				.append(meta.getUserName() + " ")
				.append(meta.getPassword() + " ").append(cmd + " ");
		String loadShell = DpExecutorUtils.getSystemPath()
				+ DataCollectionUtils
						.getProperties("com.asiainfo.dacp.dp.executor.steps.load.db2.loadshell");
		String command = loadShell + " " + params.toString();
		return command;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.asiainfo.dacp.dp.executor.Step#stop()
	 */
	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}

}
